#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <sys/fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;
class sock
{
public:
    sock(int port = 8080, const string &ip = "0.0.0.0")
        : _port(port), _ip(ip)
    {
        int listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0)
            cout << "socket fail" << endl;
        // 设置端口复用
        int opt = 1;
        setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        _listensock = listensock;
        // cout << _listensock << endl;
    }
    bool Bind()
    {
        sockaddr_in local;
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        int ret = bind(_listensock, (sockaddr *)(&local), sizeof(local));
        if (ret < 0)
        {
            cout << "bind fail" << endl;
            return false;
        }
        return true;
    }
    bool Listen()
    {
        int ret = listen(_listensock, _queue_listen);
        if (ret < 0)
        {
            cout << "listen fail" << endl;
            return false;
        }
        return true;
    }
    int Accept() const
    {
        sockaddr_in client;
        memset(&client, 0, sizeof(client));
        socklen_t len = sizeof client;
        int sock = accept(_listensock, (sockaddr *)(&client), &len);
        if (sock < 0)
        {
            cout << "accept fail" << endl;
            return -1;
        }
        return sock;
    }
    void Connect(int sock, int port, const string &ip)
    {
        sockaddr_in serve;
        memset(&serve, 0, sizeof(serve));
        serve.sin_addr.s_addr = inet_addr(ip.c_str());
        serve.sin_family = AF_INET;
        serve.sin_port = htons(port);
        int ret = connect(sock, (sockaddr *)(&serve), sizeof(serve));
        if (ret < 0)
            cout << "connect fail" << endl;
    }
    ~sock()
    {
        if (_listensock > 0)
            close(_listensock);
    }

private:
    int _port;
    const string &_ip;
    const static int _queue_listen = 20;

public:
    int _listensock;
};
